package pri.zjy.concurrent;

/**
 * @author zhangjy
 * @description 多线程交替打印
 * <p>
 * volatile控制打印标识，获取到标识的线程才能打印
 * @date 2025/5/7 21:51
 */
public class AlternatePrint3 {

    static int num = 1;

    static int limit = 10;

    static volatile boolean flag = true;

    public static void main(String[] args) {
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                while (num <= limit) {
                    if (flag) {
                        System.out.println(getName() + "---" + num);
                        num++;
                        flag = false;
                    }
                }
            }
        };
        thread1.start();

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                while (num <= limit) {
                    if (!flag) {
                        System.out.println(getName() + "---" + num);
                        num++;
                        flag = true;
                    }
                }
            }
        };
        thread2.start();
    }

}
